﻿using System.IO.Compression;
using System.Text;

namespace GZipInteractJS
{
    public class GZipHelper
    {
        #region 压缩
        /// <summary>
        /// 压缩
        /// </summary>
        public static async Task<byte[]> Compress(byte[] originalBytes)
        {
            using var originalStream = new MemoryStream(originalBytes);
            return await Compress(originalStream);
        }

        /// <summary>
        /// 压缩
        /// </summary>
        public static async Task<byte[]> Compress(Stream originalStream)
        {
            using var compressedStream = new MemoryStream();
            using var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress);
            await originalStream.CopyToAsync(gzipStream);
            return compressedStream.ToArray();
        }
        #endregion

        #region 解压
        /// <summary>
        /// 解压
        /// </summary>
        public static async Task<byte[]> Decompress(byte[] compressedBytes)
        {
            using var compressedStream = new MemoryStream(compressedBytes);

            return await Decompress(compressedStream);
        }

        /// <summary>
        /// 解压
        /// </summary>
        public static async Task<byte[]> Decompress(Stream compressedStream)
        {
            using var gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);

            using var decompressedStream = new MemoryStream();
            await gzipStream.CopyToAsync(decompressedStream);

            return decompressedStream.ToArray();
        }
        #endregion
    }
}
